<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2017 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 李邦琦 <1536549251@qq.com>
// +----------------------------------------------------------------------

namespace app\crm\controller;
use think\Loader;
use think\Cache;

class Servicecustomer extends CrmController
{
    /**
     * 渲染模板customerList
     */
    public function customerIndex()
    {
        $menuname = "Service Customer";
        $p_menuname = $_SESSION['menu'][$menuname]; //父菜单
        $priv = $_SESSION["user_priv"][$p_menuname][$menuname];     
        $this->assign("priv",$priv);

        $this->assign("customer_type",$_REQUEST['customer_type']);
        $this->assign("index",$_REQUEST['index']);

        // 模板输出
        return $this->fetch('customerIndex');
    }


    /**
     * 渲染模板customerList
     */
    public function customerList()
    {
        $menuname = "Service Customer";
        $p_menuname = $_SESSION['menu'][$menuname]; //父菜单
        $priv = $_SESSION["user_priv"][$p_menuname][$menuname];     
        $this->assign("priv",$priv);
        
        $this->assign("customer_type",$_REQUEST['customer_type']);
        $this->assign("customer_time",$_REQUEST['customer_time']);

        $member = Cache::get('member');
        $this->assign("member",$member);
        
        $arrUsers = Loader::model('Users')->getUsersList();
        $this->assign("arrUsers",$arrUsers);

        $arrGroups = Loader::model('Servicecustomer')->getGroupsOption();
        $this->assign("arrGroups",$arrGroups);
        // 模板输出
        return $this->fetch('customerList');
    }


    /**
     * 渲染模板customerGroups
     */
    public function customerGroups()
    {
        $menuname = "Customer Groups";
        $p_menuname = $_SESSION['menu'][$menuname]; //父菜单
        $priv = $_SESSION["user_priv"][$p_menuname][$menuname];     
        $this->assign("priv",$priv);

        // 模板输出
        return $this->fetch('customerGroups');
    }


    /**
     * 渲染模板editCustomer
     */
    public function editCustomer()
    {
        $menuname = "Service Customer";
        $p_menuname = $_SESSION['menu'][$menuname]; //父菜单
        $priv = $_SESSION["user_priv"][$p_menuname][$menuname];     
        $this->assign("priv",$priv);
        $customer_code = $_REQUEST['customer_code'];
        if (empty($customer_code)) {
            echo "页面出现未知错误！";
            exit;
        }
        $where = 'b.customer_code="'.$customer_code.'"';
        // 基本资料
        $customerData = Loader::model('Servicecustomer')->getCustomerData($where);
        // echo $where;exit;
        $customerData = $customerData['data'][0];
        // echo "<pre>";
        // print_r($customerData);exit;
        if ($customerData['sex'] == "男") {
            $customerData['option'] = '<option value="1" selected>男</option> <option value="2">女</option>';
        } elseif ($customerData['sex'] == "女") {
            $customerData['option'] = '<option value="1">男</option> <option value="2" selected>女</option>';
        } else {
            $customerData['option'] = '<option value="1">男</option> <option value="2">女</option>';
        }


        $users = Cache::get('users');
        $customerData['createuser'] = $users[$customerData['create_user']]['cn_name']."（".$customerData['create_user']."）";

        /*echo "<pre>";
        print_r($customerData);exit;*/
        $this->assign('customerData', $customerData);

        $arrGroups = Loader::model('Servicecustomer')->getGroupsOption();
        $this->assign("arrGroups",$arrGroups);

        $address = Loader::model('Servicecustomer')->getAddress($customer_code);
        $this->assign('address', $address);
        // 模板输出
        return $this->fetch('editCustomer');
    }


    /**
     * 渲染模板illness
     */
    public function illness()
    {
        $menuname = "Service Customer";
        $p_menuname = $_SESSION['menu'][$menuname]; //父菜单
        $priv = $_SESSION["user_priv"][$p_menuname][$menuname];     
        $this->assign("priv",$priv);
        $this->assign('customer_code', $_GET['customer_code']);
        // 模板输出
        return $this->fetch('illness');
    }


    /**
     * 渲染模板visit
     */
    public function visit()
    {
        $menuname = "Service Customer";
        $p_menuname = $_SESSION['menu'][$menuname]; //父菜单
        $priv = $_SESSION["user_priv"][$p_menuname][$menuname];     
        $this->assign("priv",$priv);
        $this->assign('customer_code', $_GET['customer_code']);
        // 模板输出
        return $this->fetch('visit');
    }


    /**
     * 渲染模板addIllness
     */
    public function addIllness()
    {
        $menuname = "Service Customer";
        $p_menuname = $_SESSION['menu'][$menuname]; //父菜单
        $priv = $_SESSION["user_priv"][$p_menuname][$menuname];     
        $this->assign("priv",$priv);
        $illnessSelect = Cache::get('illnessSelect');
        $illness_option = '';
        foreach ($illnessSelect as $val) {
            $illness_option .= '<option value="'.$val['id'].'">'.$val['illness_type'].'</option>';
        }
        $this->assign('illness_option', $illness_option);
        $this->assign('customer_code', $_GET['customer_code']);
        // 模板输出
        return $this->fetch('addIllness');
    }


    /**
     * 渲染模板addVisit
     */
    public function addVisit()
    {
        $menuname = "Service Customer";
        $p_menuname = $_SESSION['menu'][$menuname]; //父菜单
        $priv = $_SESSION["user_priv"][$p_menuname][$menuname];     
        $this->assign("priv",$priv);
        $this->assign('customer_code', $_GET['customer_code']);
        $result = Cache::get('visitSelect');
        // 回访类型
        $visit_type = '<option value="">请选择</option>';
        foreach ($result['visit_type'] as $val) {
            $visit_type .= '<option value="'.$val['id'].'">'.$val['visit_type'].'</option>';
        }
        $this->assign('visit_type', $visit_type);
        // 回访结果
        $visit_result = '<option value="">请选择</option>';
        foreach ($result['visit_result'] as $val) {
            $visit_result .= '<option value="'.$val['id'].'">'.$val['result_name'].'</option>';
        }
        $this->assign('visit_result', $visit_result);
        // 模板输出
        return $this->fetch('addVisit');
    }


    /**
     * 渲染模板editIllness
     */
    public function editIllness()
    {
        $menuname = "Service Customer";
        $p_menuname = $_SESSION['menu'][$menuname]; //父菜单
        $priv = $_SESSION["user_priv"][$p_menuname][$menuname];     
        $this->assign("priv",$priv);
        $id = $_REQUEST['id'];
        $result = Loader::model('Servicecustomer')->getIllnessInfo($id);
        $this->assign('illnessInfo', $result);
        $illnessSelect = Cache::get('illnessSelect');
        $illness_option = '';
        foreach ($illnessSelect as $val) {
            if ($result['illness_type'] == $val['id']) {
                $illness_option .= '<option value="'.$val['id'].'" selected>'.$val['illness_type'].'</option>';
                continue;
            }
            $illness_option .= '<option value="'.$val['id'].'">'.$val['illness_type'].'</option>';
        }
        $this->assign('illness_option', $illness_option);
        $this->assign('customer_code', $_GET['customer_code']);
        // echo $_GET['customer_code'];exit;
        // 模板输出
        return $this->fetch('editIllness');
    }


    /**
     * 渲染模板editGroup
     */
    public function editGroup()
    {
        $menuname = "Customer Groups";
        $p_menuname = $_SESSION['menu'][$menuname]; //父菜单
        $priv = $_SESSION["user_priv"][$p_menuname][$menuname];     
        $this->assign("priv",$priv);
        $data = $_REQUEST;
        // print_r($data);exit;
        $this->assign('data', $data);
        // 模板输出
        return $this->fetch('editGroup');
    }


    /**
     * 编辑分组
     */
    public function updateGroup ()
    {
        $data = $_REQUEST;
        Loader::model('Servicecustomer')->updateGroup($data);
    }


    /**
     * 渲染模板shareCustomer
     */
    public function transferCustomer()
    {
        $menuname = "Service Customer";
        $p_menuname = $_SESSION['menu'][$menuname]; //父菜单
        $priv = $_SESSION["user_priv"][$p_menuname][$menuname];     
        $this->assign("priv",$priv);
        // 读缓存 获取用户信息
        $users = Cache::get('users');
        $options = "";
        foreach ($users as $key => $val) {
            $options .= "<option value='$key'>";
            $options .= $val['cn_name'];
            $options .= "</option>";
        }
        $this->assign('options', $options);
        $customer_code = rtrim($_GET['customer_code'], '|');
        // echo $id;exit;
        $this->assign('customer_code', $customer_code);
        // 模板输出
        return $this->fetch('transferCustomer');
    }


    /**
     * 转交客户资料
     */
    public function dotransferCustomer ()
    {
        $customer_code = $_REQUEST['customer_code'];
        $create_user = empty($_REQUEST['username'])? '': $_REQUEST['username'];
        $transfer_note = $_REQUEST['transfer_note'];
        // print_r($create_user);exit;
        $customer_code = join('","',explode('|', $customer_code));
        $where = 'customer_code IN ("'.$customer_code.'")';
        $result = Loader::model('Servicecustomer')->transferCustomer($where, $create_user, $transfer_note);
        if ($result) {
            echo json_encode(array('success'=>true,'msg'=>'操作成功！'));
        } else {
            echo json_encode(array('msg'=>'操作失败！'));
        }
        // echo json_encode($ids);
    }


    /**
     * 获取客户资料列表
     * @return [json] [客户资料列表]
     */
    public function customerDataList()
    {
        // $users = Cache::get('users');
        $page = $_REQUEST["page"];
        $limit = $_REQUEST["limit"];
        // print_r($_REQUEST);exit;
        //需先判断传值是否为空
        $where = "(1 ";
        $where .= " AND recovery = 1";
        $where .= " AND create_user = '".$_SESSION['user_info']['username']."'";
        // $where .= empty($_REQUEST["dept_id"])?"":" AND dept_id = '".$_REQUEST["dept_id"]."'";
        $where .= empty($_REQUEST["customer_type"])?" AND customer_type = 'first'":" AND customer_type = '".$_REQUEST["customer_type"]."'";
        $where .= empty($_REQUEST["name"])?"":" AND name like '%".$_REQUEST["name"]."%'";
        $where .= empty($_REQUEST["import_mark"])?"":" AND import_mark like '%".$_REQUEST["import_mark"]."%'";
        $where .= empty($_REQUEST["customer_code"])?"":" AND b.customer_code like '%".$_REQUEST["customer_code"]."%'";
        $where .= empty($_REQUEST["phone"])?"":" AND phone like '%".$_REQUEST["phone"]."%'";
        $where .= empty($_REQUEST["create_user"])?"":" AND create_user = '".$_REQUEST["create_user"]."'";
        $where .= empty($_REQUEST["start_createtime"])?"":" AND createtime > '".$_REQUEST["start_createtime"]."'";
        $where .= empty($_REQUEST["end_createtime"])?"":" AND createtime < '".$_REQUEST["end_createtime"]."'";
        $where .= empty($_REQUEST["integral"])?"":" AND integral ".$_REQUEST["integral"];
        $where .= empty($_REQUEST["member_level"])?"":" AND member_level = '".$_REQUEST["member_level"]."'";
        $where .= empty($_REQUEST["order_num"])?"":" AND order_num ".$_REQUEST["order_num"];
        $where .= empty($_REQUEST["sign_num"])?"":" AND sign_num ".$_REQUEST["sign_num"];
        $where .= empty($_REQUEST["age"])?"":" AND age = '".$_REQUEST["age"]."'";
        $where .= empty($_REQUEST["sex"])?"":" AND sex = '".$_REQUEST["sex"]."'";
        $where .= empty($_REQUEST["groups"])?"":" AND groups = '".$_REQUEST["groups"]."'";
        $where .= empty($_REQUEST["id_card"])?"":" AND id_card like '%".$_REQUEST["id_card"]."%'";
        
        if ($_REQUEST["last_call_time"]) {
            $last_call_time = explode(',', $_REQUEST["last_call_time"]);
            $where .= $this->lastTime($last_call_time[0], 'last_call_time');
            $where .= $this->lastTime($last_call_time[2], 'last_call_time');
        }

        if ($_REQUEST["last_order_time"]) {
            $last_order_time = explode(',', $_REQUEST["last_order_time"]);
            $where .= $this->lastTime($last_order_time[0], 'last_order_time');
            $where .= $this->lastTime($last_order_time[2], 'last_order_time');
        }

        if ($_REQUEST['customer_time']) {
            switch ($_REQUEST['customer_time']) {
                case 'all' : break;
                case 'today' : 
                    $where .= " AND createtime > '".date('Y-m-d')." 00:00:00'";
                    break;
                case 'week' : 
                    if(date('w') == 0) {
                        $week = 6;
                    } else {
                        $week = date('w')-1;
                    }
                    // echo $week;exit;
                    $where .= " AND createtime > '".date('Y-m-d', time()-$week*24*3600)." 00:00:00'";
                    break;
                case 'month' : 
                    $where .= $this->lastTime('>30', 'last_call_time');
                    break;
                default : break;
            }
            
        }

        $where .= " )";
    
        $arrData = Loader::model('Servicecustomer')->getCustomerData($where,$page,$limit);
        echo json_encode($arrData);
    }


    protected function lastTime ($time, $key)
    {
        $where = ' ';
        if ($time) {
            $lastTime = date('Y-m-d', time() - substr($time, 1)*24*3600);
            if (substr($time, 0, 1) == '=') {
                $where .= " AND $key like '%".$lastTime."%'";
            } else if (substr($time, 0, 1) == '<') {
                $where .= " AND $key > '".$lastTime."'";
            } else {
                $where .= " AND $key < '".$lastTime."'";
            }
        }
        return $where;
    }


    /**
     * 获取分组数据
     * @return json 分组的数据内容
     */
    public function getGroups ()
    {
        $arrData = Loader::model('Servicecustomer')->getGroups();
        echo json_encode($arrData);
    }


    public function addGroup ()
    {
        $menuname = "Customer Groups";
        $p_menuname = $_SESSION['menu'][$menuname]; //父菜单
        $priv = $_SESSION["user_priv"][$p_menuname][$menuname];     
        $this->assign("priv",$priv);

        // 模板输出
        return $this->fetch('addGroup');
    }


    /**
     * 更新客户资料
     */
    public function updateCustomer () 
    {
        $data = $_REQUEST;
        $location_address = explode('/', $data['location_address']);
        $address['province'] = $location_address[0];
        $address['city'] = $location_address[1];
        $address['area'] = $location_address[2];
        $address['address_details'] = $data['address_details'];
        $address['customer_code'] = $data['customer_code'];
        $address_return = Loader::model('Servicecustomer')->updateAddressCustomer($address);
        // print_r($address);exit;

        $basic['customer_code'] = $data['customer_code'];
        if(strpos($data['phone'],"*") === false) {
            $basic['phone'] = $data['phone'];
        }
        if(strpos($data['telephone'],"*") === false) {
            $basic['telephone'] = $data['telephone'];
        }
        $basic['name'] = $data['name'];
        $basic['groups'] = $data['groups'];
        $basic_return = Loader::model('Servicecustomer')->updateBasicCustomer($basic);
        // print_r($basic);

        $detail['customer_code'] = $data['customer_code'];
        $detail['sex'] = $data['sex'];
        $detail['age'] = $data['age'];
        $detail['member_level'] = $data['member_level'];
        $detail_return = Loader::model('Servicecustomer')->updateDetailCustomer($detail);
        // print_r($detail);
        /*print_r($address_return);
        print_r($basic_return);
        print_r($detail_return);exit;*/
        if ($address_return || $basic_return || $detail_return) {
            echo json_encode(array('success'=>true,'msg'=>'保存成功！'));
        } else {
            echo json_encode(array('msg'=>'保存失败！'));
        }
    }


    /**
     * 获取地区
     */
    public function getAddress ()
    {
        $customer_code = $_REQUEST['customer_code'];
        Loader::model('Servicecustomer')->getAddress($customer_code);
    }


    /**
     * 获取客户病情信息
     */
    public function getIllness ()
    {
        $customer_code = $_REQUEST['customer_code'];
        $where = "customer_code='$customer_code'";
        $res = Loader::model('Servicecustomer')->getIllness($where);
        echo json_encode($res);
    }


    /**
     * 获取客户病情信息
     */
    public function getVisit ()
    {
        $customer_code = $_REQUEST['customer_code'];
        $where = "customer_code='$customer_code'";
        $res = Loader::model('Servicecustomer')->getVisit($where);
        echo json_encode($res);
    }


    /**
     * 新增病情
     */
    public function insertIllness ()
    {
        $data = $_REQUEST;
        $data['create_user'] = $_SESSION['user_info']['username'];
        $data['create_time'] = date('Y-m-d H:i:s');
        // print_r($data);
        Loader::model('Servicecustomer')->insertIllness($data);
    }


    /**
     * 新增回访记录
     */
    public function insertVisit ()
    {
        $data = $_REQUEST;
        $data['create_user'] = $_SESSION['user_info']['username'];
        $data['create_time'] = date('Y-m-d H:i:s');
        // print_r($data);exit;
        Loader::model('Servicecustomer')->insertVisit($data);
    }


    /**
     * 新增客户分组
     */
    public function insertGroup ()
    {
        $data = $_REQUEST;
        $data['createname'] = $_SESSION['user_info']['username'];
        // print_r($data);exit;
        Loader::model('Servicecustomer')->insertGroup($data);
    }


    /**
     * 删除客户分组
     */
    public function delGroup ()
    {
        $ids = $_REQUEST['ids'];
        $ids = rtrim($ids, ',');
        // print_r($ids);exit;
        Loader::model('Servicecustomer')->delGroup($ids);
    }


    /**
     * 更新病情
     */
    public function updateIllness()
    {
        $data = $_REQUEST;
        Loader::model('Servicecustomer')->updateIllness($data);
        // print_r($_REQUEST);
    }


    /**
     * 删除病情
     */
    public function delIllness ()
    {
        $id = $_REQUEST['ids'];
        // $id = '1|';
        $ids = explode('|', $id);
        $id_str = "(";
        foreach ($ids as $v) {
            $id_str .= $v.',';
        }
        $id_str = rtrim($id_str, ',');
        $id_str .= ")";
        $where = "id IN $id_str";
        Loader::model('Servicecustomer')->delIllness($where);
    }


    /**
     * 删除回访记录
     */
    public function delVisit ()
    {
        $id = $_REQUEST['ids'];
        // $id = '1|';
        $ids = explode('|', $id);
        $id_str = "(";
        foreach ($ids as $v) {
            $id_str .= $v.',';
        }
        $id_str = rtrim($id_str, ',');
        $id_str .= ")";
        $where = "id IN $id_str";
        Loader::model('Servicecustomer')->delVisit($where);
    }


    /**
     * 渲染模板addVisit
     */
    public function editVisit()
    {
        $menuname = "Service Customer";
        $p_menuname = $_SESSION['menu'][$menuname]; //父菜单
        $priv = $_SESSION["user_priv"][$p_menuname][$menuname];     
        $this->assign("priv",$priv);
        $id = $_GET['id'];
        $visit_info = Loader::model('Servicecustomer')->getVisitInfo($id);
        //print_r($visit_info);exit;
        $this->assign('visit_info', $visit_info);

        $this->assign('customer_code', $_GET['customer_code']);
        $result = Cache::get('visitSelect');
        // 回访类型
        $visit_type = '<option value="">请选择</option>';
        foreach ($result['visit_type'] as $val) {
            if ($visit_info['visit_type_id'] == $val['id']) {
                $visit_type .= '<option value="'.$val['id'].'" selected>'.$val['visit_type'].'</option>';
            } else {
                $visit_type .= '<option value="'.$val['id'].'">'.$val['visit_type'].'</option>';
            }
        }
        $this->assign('visit_type', $visit_type);
        // 回访结果
        $visit_result = '<option value="">请选择</option>';
        foreach ($result['visit_result'] as $val) {
            if ($visit_info['visit_result_id'] == $val['id']) {
                $visit_result .= '<option value="'.$val['id'].'" selected>'.$val['result_name'].'</option>';
            } else {
                $visit_result .= '<option value="'.$val['id'].'">'.$val['result_name'].'</option>';
            }
        }
        $this->assign('visit_result', $visit_result);
        // 模板输出
        return $this->fetch('editVisit');
    }


    /**
     * 更新病情
     */
    public function updateVisit()
    {
        // print_r($_REQUEST);exit;
        $data = $_REQUEST;
        Loader::model('Servicecustomer')->updateVisit($data);
    }



}